package com.szp.lg.blog.Controller;

import com.alibaba.fastjson.JSON;
import com.szp.lg.blog.config.props.DataSourceProps;
import com.szp.lg.blog.constant.ConstantDbZkPath;
import com.szp.lg.blog.datasource.DataSourceConfig;
import com.szp.lg.blog.pojo.Blog;
import com.szp.lg.blog.sercvice.BlogService;
import com.szp.lg.blog.util.PageQueryUtil;
import com.szp.lg.blog.util.PageResult;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Id;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import javax.xml.xpath.XPath;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Controller
//@RequestMapping("/blog")
public class BlogController implements ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(BlogController.class);
    @Autowired
    BlogService blogService;
    ApplicationContext applicationContext;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    CuratorFramework curatorFramework;

    @RequestMapping("/findAll")
    @ResponseBody
    public PageResult findAll() {
        return blogService.findAll(null);
    }

    @RequestMapping(value = {"", "/", "/index", "index.html"})
    public String index(@RequestParam(required = false) Map<String, Object> params, HttpServletRequest request) {
        if (null == params.get("page")) {
            params.put("page", "1");
        }
        if (null == params.get("limit")) {
            params.put("limit", "2");
        }
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        request.setAttribute("pageResult", blogService.findAll(pageUtil));
//        HikariDataSource hikariDataSource = applicationContext.getBean(HikariDataSource.class);
//        System.out.println(hikariDataSource);
        DataSource dataSource = DataSourceConfig.dynamicDataSource;
//        HikariDataSource dataSource = (HikariDataSource)jdbcTemplate.getDataSource();
//        System.out.println(dataSource);
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            System.out.println(beanName + ":" + applicationContext.getBean(beanName));
        }
        return "client/index";
    }

    @RequestMapping("/updateDb")
    @ResponseBody
    public String updateDb(@RequestParam Map<String, String> params) {
        String url = params.get("url");
        String username = params.get("username");
        String password = params.get("password");

        DataSourceProps prop = new DataSourceProps();
        prop.setUrl(url);
        prop.setUsername(username);
        prop.setPassword(password);


        String path = ConstantDbZkPath.DB_ZK_PATH;
        try {
            //创建节点
            String propStr = JSON.toJSONString(prop);
            Stat dataPath = curatorFramework.setData().forPath(path, propStr.getBytes());
            logger.info("使用传入的数据库信息创建节点{},返回数据{}", propStr, dataPath);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("从zk获取数据库信息失败", e);
        }
        return path;
    }

    @RequestMapping("/getDb")
    @ResponseBody
    public DataSourceProps getDb() {
        String path = ConstantDbZkPath.DB_ZK_PATH;
        try {
            //创建节点
            byte[] data = curatorFramework.getData().forPath(path);
            String dataInfo = new String(data);
            DataSourceProps props = JSON.parseObject(dataInfo, DataSourceProps.class);
            logger.info("从zk获取数据库信息{}", dataInfo);
            return props;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("从zk获取数据库信息失败", e);
        }
        return new DataSourceProps();
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
